<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>轨道日志监控系统</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f5f7fa;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            color: #2c3e50;
        }

        .controls {
            text-align: center;
            margin: 15px 0;
        }

        select {
            padding: 8px 16px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .tracks {
            display: flex;
            justify-content: space-around;
            margin: 30px 0;
            gap: 20px;
        }

        .track {
            width: 45%;
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: relative;
        }

        .track-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #2980b9;
        }

        /* 轨道示意图 */
        .track-diagram {
            height: 60px;
            background: #e0e0e0;
            border-radius: 4px;
            position: relative;
            margin: 20px 0;
        }

        .sensor {
            position: absolute;
            top: -10px;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            font-size: 12px;
        }

        .sensor-1 {
            left: 20%;
            background: #95a5a6;
        }

        /* 默认灰色 */
        .sensor-1.active {
            background: #2ecc71;
        }

        /* 触发绿色 */

        .sensor-2 {
            left: 50%;
            background: #95a5a6;
        }

        .sensor-2.active {
            background: #2ecc71;
        }

        .sensor-3 {
            left: 80%;
            background: #95a5a6;
        }

        .sensor-3.active {
            background: #2ecc71;
        }

        .status-indicator {
            margin-top: 10px;
            padding: 8px;
            border-radius: 4px;
            text-align: center;
            font-weight: bold;
        }

        .status-ok {
            background: #d4edda;
            color: #155724;
        }

        .status-ng {
            background: #f8d7da;
            color: #721c24;
        }

        .status-idle {
            background: #e2e3e5;
            color: #41464b;
        }

        .log-container {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            height: 300px;
            overflow-y: auto;
            margin-top: 20px;
        }

        .log-item {
            padding: 6px 0;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }

        .log-time {
            color: #6c757d;
            font-size: 12px;
        }

        .highlight-ok {
            color: #28a745;
        }

        .highlight-ng {
            color: #dc3545;
        }

        .highlight-scan {
            color: #007bff;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>轨道日志监控系统</h1>

    <div class="controls">
        <label for="trackSelect">选择轨道：</label>
        <select id="trackSelect">
            <option value="1">轨道 1</option>
            <option value="2">轨道 2</option>
        </select>
    </div>

    <div class="tracks">
        <div class="track" id="track1">
            <div class="track-title">轨道 1</div>
            <div class="track-diagram">
                <div class="sensor sensor-1" id="sensor1-1">S1</div>
                <div class="sensor sensor-2" id="sensor1-2">S2</div>
                <div class="sensor sensor-3" id="sensor1-3">S3</div>
            </div>
            <div class="status-indicator status-idle" id="status1">空闲</div>
        </div>

        <div class="track" id="track2">
            <div class="track-title">轨道 2</div>
            <div class="track-diagram">
                <div class="sensor sensor-1" id="sensor2-1">S1</div>
                <div class="sensor sensor-2" id="sensor2-2">S2</div>
                <div class="sensor sensor-3" id="sensor2-3">S3</div>
            </div>
            <div class="status-indicator status-idle" id="status2">空闲</div>
        </div>
    </div>

    <div class="log-container" id="logContainer">
        <!-- 日志动态插入 -->
    </div>
</div>

<script>
    // WebSocket 连接
    const ws = new WebSocket('ws://localhost:8080/ws'); // 请根据实际地址修改
    const logContainer = document.getElementById('logContainer');
    const trackSelect = document.getElementById('trackSelect');

    let selectedTrack = 1;

    trackSelect.addEventListener('change', () => {
        selectedTrack = parseInt(trackSelect.value);
        // 可选：清空日志或高亮当前轨道
    });

    // 日志缓存（用于切换轨道时重显）
    const logs = [];

    function addLog(log) {
        logs.push(log);
        renderLogs();
    }

    function renderLogs() {
        // 只显示所选轨道的日志
        const filtered = logs.filter(log => log.track === selectedTrack);
        logContainer.innerHTML = filtered.map(log => {
            let cls = '';
            if (log.event === 'command') {
                cls = log.status === 'OK' ? 'highlight-ok' : 'highlight-ng';
            } else if (log.event === 'scan') {
                cls = 'highlight-scan';
            }
            return `<div class="log-item">
          <span class="log-time">[${log.timestamp}]</span>
          <span class="${cls}">${log.message}</span>
        </div>`;
        }).join('');
        // 自动滚动到底部
        logContainer.scrollTop = logContainer.scrollHeight;
    }

    // 更新传感器状态
    function updateSensor(track, sensorIndex, active) {
        const el = document.getElementById(`sensor${track}-${sensorIndex}`);
        if (el) {
            el.classList.toggle('active', active);
        }
    }

    // 更新轨道状态（OK/NG/空闲）
    function updateTrackStatus(track, status) {
        const el = document.getElementById(`status${track}`);
        if (!el) return;
        el.textContent = status;
        el.className = 'status-indicator ' +
            (status === 'OK' ? 'status-ok' :
                status === 'NG' ? 'status-ng' : 'status-idle');
    }

    // 模拟：根据事件更新 UI
    function handleEvent(data) {
        const {track, event, status, message, timestamp} = data;

        // 更新日志
        addLog({track, event, status, message, timestamp});

        // 更新传感器（假设 sensor 事件中 status 是传感器编号）
        if (event === 'sensor') {
            const sensorNum = parseInt(status);
            if (!isNaN(sensorNum) && sensorNum >= 1 && sensorNum <= 3) {
                updateSensor(track, sensorNum, true);
                // 3秒后自动熄灭（可选）
                setTimeout(() => updateSensor(track, sensorNum, false), 3000);
            }
        }

        // 更新轨道最终状态
        if (event === 'command') {
            updateTrackStatus(track, status);
            // 5秒后恢复空闲
            setTimeout(() => updateTrackStatus(track, '空闲'), 5000);
        }
    }

    // WebSocket 消息处理
    ws.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);
            // 预期字段：track, event, status, message, timestamp
            if (data.track && data.event) {
                handleEvent(data);
            }
        } catch (e) {
            console.error('Invalid WebSocket message:', event.data);
        }
    };

    ws.onopen = () => {
        console.log('WebSocket connected');
        addLog({track: 1, message: 'WebSocket 连接成功', timestamp: new Date().toLocaleTimeString(), event: 'system'});
    };

    ws.onerror = (err) => {
        console.error('WebSocket error:', err);
        addLog({
            track: 1,
            message: '❌ WebSocket 连接失败',
            timestamp: new Date().toLocaleTimeString(),
            event: 'system'
        });
    };

    ws.onclose = () => {
        console.log('WebSocket disconnected');
        addLog({track: 1, message: '⚠️ WebSocket 已断开', timestamp: new Date().toLocaleTimeString(), event: 'system'});
    };
</script>
</body>
</html>